﻿namespace JanusLibAing.AutoSave
{
    using System;
    using System.IO;
    using System.Timers;

    public class AutoSaver : XmlStorage
    {
        public const string AutoSaveFileExt = ".xml";                 //MLHIDE
        public const string AutoSaveFolder = "AutoSave\\";            //MLHIDE
        private int saveInterval = 5;
        private Timer timer;
        private string fileName;

        public event EventHandler<AutoSaveEventArgs> OnSaveData;
        public event EventHandler<ErrorEventArgs> OnError;


        public AutoSaver(XmlStorageFactory itemsFactory, string fileName)
            : base(AutoSaveFolder, AutoSaveFileExt, itemsFactory)
        {
            timer = new Timer(saveInterval * 1000);
            timer.AutoReset = true;
            timer.Elapsed += timer_Elapsed;
            this.fileName = fileName;
        }

        private bool InvokeOnSaveData(AutoSaveEventArgs e)
        {
            bool ret = false;
            EventHandler<AutoSaveEventArgs> handler = OnSaveData;
            if (handler != null)
            {
                handler(this, e);
                ret = true;
            }
            return ret;
        }

        public void InvokeOnError(ErrorEventArgs e)
        {
            EventHandler<ErrorEventArgs> handler = OnError;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        /// <summary>
        /// Deletes stored file.
        /// </summary>
        public void Delete()
        {
            Stop();
            string completeSavePath;
            string fullFileName = GetFullFileName(fileName, out completeSavePath);
            try
            {
                File.Delete(fullFileName);
            }
            catch (Exception ex)
            {
                InvokeOnError(new ErrorEventArgs(ex));
            }
        }

        public void Start()
        {
            timer.Start();
        }

        public void Stop()
        {
            timer.Stop();
        }

        public void Load()
        {
            Load(fileName);
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            AutoSaveEventArgs arg = new AutoSaveEventArgs();
            bool handlerPresent = InvokeOnSaveData(arg);
            if (!arg.Cancel && handlerPresent)
            {
                Write(fileName);
            }
        }

        public int SaveInterval
        {
            get
            {
                return saveInterval;
            }

            set
            {
                saveInterval = value;
                timer.Interval = saveInterval * 1000;
            }
        }
    }
}
